/*
 * @Author: 我想吃余 483766615@qq.com
 * @Date: 2025-10-17 14:10:24
 * @LastEditors: 我想吃余 483766615@qq.com
 * @LastEditTime: 2025-10-18 09:43:19
 * @FilePath: /code/OScode/pipe/TestPipe.cpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include <iostream>
#include <string>
#include <cstdio>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

using namespace std;

#define N 2
#define NUM 1024

//child
void Read(int rfd)
{
    char buffer[NUM];
    while(true)
    {
        int n = read(rfd, buffer, sizeof(buffer));   
        if(n > 0)
        {
            buffer[n] = 0;//设置字符串末尾\0
            cout<< "child get a message[" << buffer << "]" << endl;
        }
        else if(n == 0)
        {
            printf("child get fail\n");
            break;
        }
        else break;
    }
}

//father
void Write(int wfd)
{
    std::string s("I am father");
    pid_t self = getpid();
    int numbers = 0;
    char buffer[NUM];
    while(true)
    {
        buffer[0] = 0;//清空字符串，并表明这个数组当做字符串了
        snprintf(buffer, sizeof(buffer), "%s-%d-%d", s.c_str(), self, numbers++);
        write(wfd, buffer, strlen(buffer));
        sleep(1);

        if(numbers > 5) break;
    }
}

int main()
{
    //先创建管道
    int pipefd[N] = {0};
    int n = pipe(pipefd);
    if(n < 0) return 1;
    //创建子进程
    pid_t id = fork();
    if(id < 0) return 2;
    if(id == 0)
    {
        //child
        close(pipefd[1]);
        //子进程在管道中读
        Read(pipefd[0]);
        close(pipefd[0]);
        exit(0);
    }
    //father
    close(pipefd[0]);
    Write(pipefd[1]);
    //wait child
    pid_t rid = waitpid(id, nullptr, 0);
    if(rid < 0) return 3;

    close(pipefd[1]);

    return 0;
}